package com.yilin.platform.controller.truck;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.reflect.TypeToken;
import com.yilin.platform.base_core.application.BaseController;
import com.yilin.platform.base_core.application.PageData;
import com.yilin.platform.base_core.application.ReturnData;
import com.yilin.platform.base_core.commons.annotation.Explain;
import com.yilin.platform.base_core.commons.annotation.NotNull;
import com.yilin.platform.base_core.commons.annotation.SkipLoginVerify;
import com.yilin.platform.base_core.commons.annotation.UserTarget;
import com.yilin.platform.base_core.commons.entity.AuthStatus;
import com.yilin.platform.base_core.commons.utils.DateTimeUtil;
import com.yilin.platform.base_core.commons.utils.JsonUtil;
import com.yilin.platform.base_core.commons.utils.ParamUtil;
import com.yilin.platform.base_core.commons.utils.StringUtil;
import com.yilin.platform.entity.enums.user.OrganType;
import com.yilin.platform.entity.enums.user.RoleType;
import com.yilin.platform.entity.enums.user.UserType;
import com.yilin.platform.entity.truck.TransportLicense;
import com.yilin.platform.entity.truck.TravelLicense;
import com.yilin.platform.entity.truck.TruckVehicle;
import com.yilin.platform.entity.user.Account;
import com.yilin.platform.entity.user.Organize;
import com.yilin.platform.entity.user.auth.DrivingLicense;
import com.yilin.platform.entity.user.auth.IdCard;
import com.yilin.platform.service.impl.truck.TruckVehicleService;
import com.yilin.platform.service.impl.user.AccountService;
import com.yilin.platform.service.impl.user.AuthService;
import com.yilin.platform.service.impl.user.OrganizeService;
import com.yilin.platform.service.truck.ITruckVehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 车辆控制器
 *
 * @author zhangjinyuan
 * @date 2022/10/24
 */
@RestController
@RequestMapping("/truck/vehicle/")
public class TruckVehicleController extends BaseController {
    @Resource
    ITruckVehicleService vehicleService;

    @Resource
    AccountService accountService;
    @Resource
    OrganizeService organizeService;
    @Resource
    AuthService authService;
    @Autowired
    private TruckVehicleService truckVehicleService;

    /**
     * 获取车辆分页
     */
    @PostMapping(value = "getTruckVehiclePage")
    public ReturnData<PageData<TruckVehicle>> getTruckVehiclePage(TruckVehicle query, @Explain("页码") Integer page, @Explain("条数") Integer limit) {
        PageData<TruckVehicle> pageData = vehicleService.getTruckVehiclePage(getLoginUser(), query, page, limit);
        return jsonView(true, "获取成功", pageData);
    }




    /**
     * 根据车辆ID获取车辆
     */
    @PostMapping(value = "getVehicleById")
    @NotNull("vehicleId")
    @SkipLoginVerify
    public ReturnData<TruckVehicle> getVehicleById(@Explain("车辆ID") String vehicleId) {
        TruckVehicle truckVehicle = vehicleService.getById(vehicleId);
        return jsonView(true, "获取成功", truckVehicle);
    }

    /**
     * 根据车牌号获取车辆信息
     */
    @PostMapping(value = "getTruckByTruckNo")
    @NotNull("trackNo")
    public ReturnData<TruckVehicle> getTruckByTruckNo(@Explain("车牌号") String trackNo) {
        TruckVehicle truckVehicle = vehicleService.getOne(new QueryWrapper<TruckVehicle>().eq("track_no", trackNo));
        return jsonView(true, "获取成功", truckVehicle);
    }

    /**
     * 获取组织车辆列表
     * 查询组织所有车辆时status字段为空
     */
    @PostMapping(value = "getVehicleListByOrganizeId")
    public ReturnData<List<TruckVehicle>> getVehicleListByOrganizeId(String organizeId, TruckVehicle query) {
        if (StringUtil.isEmpty(organizeId)) organizeId = getLoginUser().getOrganizeId();
        List<TruckVehicle> truckVehicleList = vehicleService.getVehicleListByOrganizeId(organizeId, query);
        return jsonView(true, "获取成功", truckVehicleList);
    }

    /**
     * 获取组织空闲车辆列表
     */
    @PostMapping(value = "getUnUsedVehicleListByOrganizeId")
    @SkipLoginVerify
    public ReturnData<List<TruckVehicle>> getUnUsedVehicleListByOrganizeId(String organizeId) {
        List<TruckVehicle> truckVehicleList = vehicleService.getUnUsedVehicleListByOrganizeId(organizeId);
        return jsonView(true, "获取成功", truckVehicleList);
    }

    /**
     * 获取驾驶员车辆
     * 查询组织所有车辆时status字段为空
     */
    @PostMapping(value = "getVehicleListByDriverId")
    public ReturnData<List<TruckVehicle>> getVehicleListByDriverId(String driverId) {
        if (StringUtil.isEmpty(driverId)) driverId = getLoginUser().getId();
        List<TruckVehicle> truckVehicleList = vehicleService.getVehicleListByDriverId(driverId);
        return jsonView(true, "获取成功", truckVehicleList);
    }

    /**
     * 保存车辆 此方法参数不能传对象，字段重复会导致错误
     */
    @PostMapping(value = "saveTruckVehicle")
    @NotNull({"vehicleJson", "travelLicenseJson"})
    @UserTarget({UserType.truckerUser})
    public ReturnData<String> saveTruckVehicle(String vehicleJson, String travelLicenseJson, String transportLicenseJson) {
        Organize organize=null;
        if(getLoginUser().getOrganType()== OrganType.company){
             organize=organizeService.getOrganizeById(getLoginUser().getOrganizeId());
        }else{
            organize=organizeService.getOrganizeById(getLoginUser().getSuperiorPlatId());
        }
        ParamUtil.isNull(organize,"获取组织信息失败");
        IdCard idCard = authService.getIdCardByUserId(getLoginUser().getId());
        ParamUtil.isNull(idCard, "您还没有认证身份证，请先认证身份证");
        Long count=vehicleService.getOrganzieByListCount(organize);
        if((count+1)>organize.getTruckNumber()) return jsonErrView("你的组织车辆数量已满额 ！");
        if (getLoginUser().getRoleType() != RoleType.manager) return jsonErrView("仅管理员允许添加车辆 ！");
        TruckVehicle truckVehicle = JsonUtil.jsonToObject(vehicleJson, new TypeToken<TruckVehicle>() {
        });
        ParamUtil.isNull(truckVehicle, "车辆JSON转换失败");
        ParamUtil.isNull(truckVehicle.getTruckEnergyTypeId(), "请选择能源类型");
        ParamUtil.isNull(truckVehicle.getTruckTypeId(), "请选择车辆类型");
        ParamUtil.isNull(truckVehicle.getCardPlateId(), "请选择车牌颜色");
        ParamUtil.isNull(truckVehicle.getVehicleImageUrl(), "请上传车辆图片");
        TravelLicense travelLicense = JsonUtil.jsonToObject(travelLicenseJson, new TypeToken<TravelLicense>() {
        });
        ParamUtil.isNull(travelLicense, "行驶证JSON转换失败");
        travelLicense.setVehicleNo(truckVehicle.getTrackNo());
        ParamUtil.isNull(travelLicense.getTravelPhotoPositiveImg(), "请上传行驶证主页");
        ParamUtil.isNull(travelLicense.getTravelPhotoBackImg(), "请上传行驶证副业");
        if (truckVehicle.getId() != null) {
            TruckVehicle vehicleByNo = vehicleService.getById(truckVehicle.getId());
            if (vehicleByNo != null && vehicleByNo.getTruckStatus() == TruckVehicle.TruckStatus.using) {
                return jsonErrView("车辆忙碌中不可修改车辆 ！");
            }
        }
        TransportLicense transportLicense = null;
        if (StringUtil.isNotEmpty(transportLicenseJson)&&transportLicenseJson.length()>5) {
            transportLicense = JsonUtil.jsonToObject(transportLicenseJson, new TypeToken<TransportLicense>() {
            });
        }
        vehicleService.saveTruckVehicle(getLoginUser(), truckVehicle, travelLicense, transportLicense);
        return jsonView(true, "保存车辆成功 ！");
    }

    /**
     * 绑定挂车
     */
    @PostMapping(value = "bindTrackor")
    @NotNull({"truckId", "trackNo"})
    public ReturnData<Object> bindTrackor(@Explain("车辆ID") String truckId, @Explain("挂车车牌") String trackNo) {
        TruckVehicle truckVehicle = vehicleService.getOne(new QueryWrapper<TruckVehicle>().eq("id", truckId));
        ParamUtil.isNull(truckVehicle, "车辆获取失败");
        truckVehicle.setTractorNo(trackNo);
        vehicleService.saveOrUpdate(truckVehicle);
        return jsonView(true, "保存车辆成功 ！");
    }

    /**
     * 绑定驾驶员
     */
    @PostMapping(value = "bindTruckUser")
    @NotNull({"truckId", "truckUserId"})
    public ReturnData<String> bindTruckUser(@Explain("车辆ID") String truckId, @Explain("司机ID") String truckUserId) {
        ParamUtil.notEquals("无权操作", getLoginUser().getUserType(), UserType.truckerUser);
        ParamUtil.notEquals("你不是管理员不能操作", getLoginUser().getRoleType(), RoleType.manager);
        TruckVehicle truckVehicle = vehicleService.getById(truckId);
        ParamUtil.equals("车辆正在使用，不能更换驾驶员，但是驾驶员可以在运输中申请换车", truckVehicle.getTruckStatus(), TruckVehicle.TruckStatus.using);
//        if (StringUtil.isNotEmpty(truckVehicle.getTruckUserId()) && truckVehicle.getTruckUserId().equals(truckUserId)) {
//            return jsonView(false, "该车辆已绑定该司机");
//        }
        Account truckUser =accountService.getAccountById(truckUserId);
        ParamUtil.isNull(truckUser, "未查询到该司机");
        IdCard idCard = authService.getIdCardByUserId(truckUser.getId());
        ParamUtil.isNull(idCard, "该用户未认证身份证");
//        ParamUtil.notEquals("该用户身份证未认证成功，不能绑定车辆", idCard.getAuthStatus(), AuthStatus.authSuccess);
        //检查驾驶员年龄是否在18-60之间
        if (idCard.getBirthday() == null)
            idCard.setBirthday(DateTimeUtil.stringToDate(idCard.getIdCardNo().substring(6, 14), "yyyyMMdd"));
        int age = DateUtil.ageOfNow(idCard.getBirthday());
        if (age < 18 || age > 60) {
            return jsonView(false, "驾驶员年龄应在18—60岁之间！");
        }
        DrivingLicense license = authService.getDrivingLicenseByUserId(truckUserId);
        ParamUtil.isNull(license, "该用户未认证驾驶证");
        ParamUtil.notEquals("该用户驾驶证未认证成功，不能绑定车辆", license.getAuthStatus(), AuthStatus.authSuccess);
//        if (truckVehicle.getVehicleWeight() > 4.5) {
//            QualificationCert cert = userRemote.getQualificationCertByUserId(truckUserId).getData();
//            ParamUtil.isNull(cert, "该用户未认证从业资格证，不能绑定总质量大于4.5吨车辆");
//            ParamUtil.notEquals("该用户从业证未认证成功，不能绑定总质量大于4.5吨车", license.getAuthStatus(), AuthStatus.authSuccess);
//        }
        TruckVehicle originalTruckVehicle = vehicleService.getOne(new QueryWrapper<TruckVehicle>().eq("truck_user_id", truckUser.getId()));
//        if (originalTruckVehicle != null && originalTruckVehicle.getTruckStatus() == TruckVehicle.TruckStatus.using) {
//            return jsonView(false, String.format("驾驶员已绑车辆:%s 正在忙碌中，不能更换车辆", originalTruckVehicle.getTrackNo()));
//        }
        vehicleService.bindTruckUser(getLoginUser(), truckUser, truckVehicle, originalTruckVehicle);
        return jsonView(true, "绑定成功！");
    }

    /**
     * 更换组织
     */
    @PostMapping(value = "updateVehicleTruckId")
    @NotNull({"vehicleId"})
    public ReturnData<String> updateVehicleTruckId(String vehicleId, String accountId) {
       if(getLoginUser().getUserType()!=UserType.platformUser&&getLoginUser().getUserType()!=UserType.adminUser){
           return jsonView(false, "你没有权限");
       }
        TruckVehicle truckVehicle = vehicleService.getById(vehicleId);
        ParamUtil.isNull(truckVehicle, "未查询到该车辆");
        Account account= accountService.getAccountById(accountId);
        ParamUtil.isNull(account,"获取用户失败");
        truckVehicle.setOrganizeId(account.getOrganizeId());
        truckVehicle.setOrganizeName(account.getOrganizeName());
        truckVehicle.setOrganizeLogo(account.getOrganizeLogo());
        truckVehicle.setManageUserAvatar(account.getAvatar());
        truckVehicle.setManageUserId(account.getId());
        truckVehicle.setManageUserName(account.getName());
        truckVehicle.setManageUserPhone(account.getPhone());
        truckVehicle.setTruckUserId(account.getId());
        truckVehicle.setTruckUserName(account.getName());
        truckVehicle.setTruckUserAvatar(account.getAvatar());
        truckVehicle.setTruckUserPhone(account.getPhone());
        truckVehicleService.updateById(truckVehicle);
        return jsonView(true, "修改成功");
    }

    /**
     * 更新车辆状态
     * 更新车辆ETC备案状态
     * 更新车辆TMS数据创建状态
     */
    @PostMapping(value = "updateVehicleStatus")
    @NotNull({"vehicleId"})
    public ReturnData<String> updateVehicleStatus(String vehicleId, TruckVehicle param) {
        TruckVehicle localTruckVehicle = vehicleService.getById(vehicleId);
        ParamUtil.isNull(localTruckVehicle, "未查询到该车辆");
        if (getLoginUser().getUserType() == UserType.truckerUser && !getLoginUser().getOrganizeId().equals(localTruckVehicle.getOrganizeId())) {
            return jsonView(false, "无权操作");
        }
        if (param.getTruckStatus() != null) localTruckVehicle.setTruckStatus(param.getTruckStatus());
        vehicleService.updateById(localTruckVehicle);
        return jsonView(true, "修改成功");
    }

    /**
     * 通过驾驶员更新车辆定位
     */
    @PostMapping("updateVehiclePosition")
    @NotNull({"position"})
    @UserTarget(UserType.truckerUser)
    public ReturnData<Object> updateVehiclePosition(@Explain("司机ID") String truckUserId, @Explain("位置信息") String position) {
        List<TruckVehicle> vehicleList = vehicleService.getVehicleListByDriverId(truckUserId);
        if (position == null) return jsonView(false, "定位为空");
        for (TruckVehicle vehicle : vehicleList) {
            vehicle.setTruckPosition(position);
//            String address = ParamUtil.isSuccess(gpsRemote.getAddressByPoint(vehicle.getPlatId(), position));
//            vehicle.setTruckAddress(address);
        }
        if (vehicleList.size() > 0) vehicleService.updateBatchById(vehicleList);
        return jsonView(true, "更新定位成功");
    }


    /**
     * 根据车辆ID数组获取车辆
     * 批量获取车辆信息
     */
    @PostMapping(value = "getVehicleListByIds")
    @NotNull("vehicleIds")
    public ReturnData<List<TruckVehicle>> getVehicleListByIds(@Explain("车辆ID数组") String[] vehicleIds) {
        List<TruckVehicle> truckVehicleList = vehicleService.listByIds(Arrays.asList(vehicleIds));
        return jsonView(true, "获取公共车辆类型Id成功", truckVehicleList);
    }

    /**
     * 更新车辆
     */
    @PostMapping(value = "updateVehicle")
    @NotNull("id")
    public ReturnData<String> updateVehicle(TruckVehicle vehicle) {
        Account loginUser = getLoginUser();
        TruckVehicle localVehicle = vehicleService.getById(vehicle.getId());
        ParamUtil.isNull(localVehicle, "未查询到该车辆");
        if (!Objects.equals(localVehicle.getTrackNo(), vehicle.getTrackNo())) {
            List<TruckVehicle> byNo = vehicleService.list(new QueryWrapper<TruckVehicle>().eq("track_no", vehicle.getTrackNo()));
            if (byNo != null) {
                return jsonView(false, "车牌号已存在");
            }
        }
        if (localVehicle.getTruckStatus() == TruckVehicle.TruckStatus.using) {
            return jsonView(false, "忙碌中不可修改!");
        }
        if (loginUser.getUserType() == UserType.truckerUser && !loginUser.getOrganizeId().equals(localVehicle.getOrganizeId())) {
            return jsonView(false, "无权操作");
        }
//        if (loginUser.getUserType() == UserType.platformUser && !loginUser.getOrganizeId().equals(localVehicle.getPlatId())) {
//            return jsonView(false, "无权操作");
//        }
        vehicleService.updateById(vehicle);
        return jsonView(true, "修改成功");
    }

    /**
     * 车辆注销
     */
    @PostMapping(value = "deleteVehicle")
    @NotNull("id")
    public ReturnData<String> deleteVehicle(TruckVehicle vehicle) {
        Account loginUser = getLoginUser();
        TruckVehicle localVehicle = vehicleService.getVehicleByNo(vehicle.getTrackNo());
        ParamUtil.isNull(localVehicle, "未查询到该车辆");
        if (loginUser.getUserType() == UserType.truckerUser && !loginUser.getOrganizeId().equals(localVehicle.getOrganizeId())) {
            return jsonView(false, "无权操作");
        }
        if (localVehicle.getTruckStatus() == TruckVehicle.TruckStatus.using) {
            return jsonView(false, "忙碌中不可修改!");
        }
//        if (loginUser.getUserType() == UserType.platformUser && !loginUser.getOrganizeId().equals(localVehicle.getPlatId())) {
//            return jsonView(false, "无权操作");
//        }
        vehicleService.removeById(vehicle);
        return jsonView(true, "注销成功");
    }


    /**
     * 车辆换绑
     */
    @PostMapping(value = "editBindVehcle")
    public ReturnData<String> editBindVehcle(String vehicleId,String organizeId) {
        ParamUtil.isNull(vehicleId,"车辆id不能为空");
        ParamUtil.isNull(organizeId,"用户id不能为空");
        TruckVehicle localVehicle = vehicleService.getVehicleById(vehicleId);
        ParamUtil.isNull(localVehicle, "未查询到该车辆");
        Organize organize=organizeService.getOrganizeById(organizeId);
        ParamUtil.isNull(organize, "未查询到该组织");
        vehicleService.editBindVehicle(organize,localVehicle);
        return jsonView(true, "注销成功");
    }


}
